<?php
class UsersController extends Zend_Controller_Action
{
    protected $_flashMessenger = null;

    public function init()
    {
        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->initView();
    }
    
    public function indexAction()
    {
    	$this->_forward('login');
    }
    
	public function loginAction()
	{
        $form = new LoginForm;

        if (!$this->getRequest()->isPost() || !$form->isValid($_POST)) {
            $this->view->loginForm = $form; 
            return;
        }

        $values = $form->getValues();

        // Setup DbTable adapter
        $adapter = new Zend_Auth_Adapter_DbTable(
            Zend_Db_Table::getDefaultAdapter() // set earlier in Bootstrap
        );
        $adapter->setTableName('person.users');
        $adapter->setIdentityColumn('login');
        $adapter->setCredentialColumn('password');
        $adapter->setIdentity($values['login']);
        $adapter->setCredential(hash('MD5', $values['password']));

        // authentication attempt
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($adapter);

        // authentication succeeded
        if ($result->isValid()) {
            $auth->getStorage()
                ->write($adapter->getResultRowObject(null, 'password'));
            $this->view->passedAuthentication = true;
            $this->_flashMessenger->addMessage('You have been successfully authenticated as ' . $values['login'] . '!');
            $this->_helper->redirector('index', 'index', 'admin');
        } else { // or not! Back to the login page!
            $this->view->failedAuthentication = true;
            $this->view->loginForm = $form;
        }         
        
	}
	
	public function logoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
		$this->_flashMessenger->addMessage('You have been successfully logged out!');
		$this->_helper->redirector('index', 'index');
	}
}